import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

packageName = ""
className = ""
projectName = ""
upperCaseProjectName = ""
mapperName = ""


FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
  className = javaName(table.getName(), true)+""
  className = className.replaceFirst("Pontiac","")
  table
  packageName = getPackageName(dir)
  projectName = getProjectName(dir)
  mapperName = getMapperName(className)
  upperCaseProjectName = getUpperCaseProjectName(projectName)
  new File(dir, className + "Repo.java").withPrintWriter { out -> out.write((new String(generateContent(out, className).getBytes("UTF-8"))))  }
}


/**
 * 获取包名称
 * @param dir 实体类所在目录
 * @return
 */
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "").replaceAll("mapper","")
}

def getProjectName(dir) {
  return dir.toString().replaceAll("\\\\", ".")
          .replaceAll("^.*src(\\.main\\.java\\.)?", "")
          .replaceAll("(com\\.pajk\\.)?","")
          .split("\\.")[0]
}

def getMapperName(className) {
  def firstStr = className.substring(0,1).toLowerCase()
  def nextStr = className.substring(1,className.size())
  return firstStr+nextStr
}

def getUpperCaseProjectName(upperCaseProjectName) {
  def firstStr = upperCaseProjectName.substring(0,1).toUpperCase()
  def nextStr = upperCaseProjectName.substring(1,upperCaseProjectName.size())
  return firstStr+nextStr
}

def generateContent(out, className) {

  def sb = new StringBuffer();
  sb.append("package ${packageName};\n")
  sb.append("\n")
  sb.append("import javax.annotation.Resource;\n")
  sb.append("import org.springframework.stereotype.Component;\n")
  sb.append("import com.pajk.${projectName}.core.dal.mapper.${className}Mapper;\n")
  sb.append("import com.pajk.${projectName}.core.dal.model.${className}DO;\n")
  sb.append("import com.pajk.${projectName}.api.exception.${upperCaseProjectName}Exception;\n")
  sb.append("import com.pajk.${projectName}.api.exception.ErrorCode;\n")
  sb.append("\n")

  sb.append("@Component\n")
  sb.append("public class ${className}Repo {\n")
  sb.append("\n")
  sb.append("\t@Resource\n")
  sb.append("\tprivate ${className}Mapper ${mapperName}Mapper;\n")
  sb.append("\n")
  sb.append("\tpublic void insert(${className}DO param){\n");
  sb.append("\t\tif (${mapperName}Mapper.insert(param) <= 0) {\n")
  sb.append("\t\t\tthrow new ${upperCaseProjectName}Exception(ErrorCode.DB_ERROR);\n")
  sb.append("\t\t}\n")
  sb.append("\t}\n")
  sb.append("\n")
  sb.append("\tpublic void update(${className}DO param){\n");
  sb.append("\t\tif (${mapperName}Mapper.update(param) <= 0) {\n")
  sb.append("\t\t\tthrow new ${upperCaseProjectName}Exception(ErrorCode.DB_ERROR);\n")
  sb.append("\t\t}\n")
  sb.append("\t}\n")
  sb.append("\n")
  sb.append("\tpublic ${className}DO getById(Long id){\n");
  sb.append("\t\treturn ${mapperName}Mapper.getById(id);\n")
  sb.append("\t}\n")
  sb.append("\n")
  sb.append("}\n")
  return sb.toString();
}

def javaName(str, capitalize) {
  def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
          .join("").replaceAll(/\_/, "")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}